Async And Await In Js

Posted on June 14, 2025 by Vishesh Namdev
Python C C++ Javascript Java
Async and Await in js

Async & Await in JS

In this article, we will learn about async and await in JavaScript. We will also learn about th ier use cases and how to use them in real-world scenarios. We will also learn about the differenc between async and await and how to use them together.

Async

Async is a keyword in JavaScript that is used to define asynchronous functions. It is used to run a function in the background without blocking the main thread of the program. The async function returns a promise that can be used to handle the result of the function.

Example:-

async function greet() {
    return "Hello!";
}
greet().then(console.log); // Logs: Hello!

Await

Await is a keyword in JavaScript that is used to pause the execution of a function until a promis is resolved or rejected. It is used to wait for the result of an asynchronous function. The await keyword can only be used inside an async function.

Why Async/Await?

  • Async/await is used to handle asynchronous code in a synchronous way.
  • It makes the code look like synchronous code but it is still asynchronous.
  • It is used to improve the performance of the program by running the code in the background without blocking the main thread of the program.
  • It is also used to handle errors in a better way.
  • Example of Async and Await

    async function shoppingFlow() {
        function placeOrder() {
            return new Promise(resolve => {
                setTimeout(() => {
                    console.log(" Order placed");
                    resolve("Package delivered");
                }, 2000); // 2 seconds
            });
        }
    
        function openPackage(packageInfo) {
            return new Promise(resolve => {
                setTimeout(() => {
                    console.log(` Opened: ${packageInfo}`);
                    resolve("Item used");
                }, 7000); // 7 seconds
            });
        }
    
        console.log(" Starting online shopping...");
        const delivery = await placeOrder();     // Takes 2 sec
        const result = await openPackage(delivery); // Takes 7 sec
        console.log(" Done:", result);
    }
    
    console.log("Welcome to myCart.com");
    shoppingFlow();
    Welcome to myCart.com
     Starting online shopping...
     Order placed         
     Opened: Package delivered 
     Done: Item used

    Explanation:-

  • In the above example, the shoppingFlow function is an async function.
  • It calls the placeOrder function which returns a promise.
  • The await keyword is used to wait for the result of the promise.
  • Once the promise is resolved, it calls the openPackage function which also returns a promise.
  • The await keyword is used again to wait for the result of the promise.
  • The result of the promise is then logged to the console.
  • Error Handling in Async and Await

    Async and await provides a cleaner way to handle errors. If an error occurs in the promise, it is thrown as an exception.This exception can be caught using a try-catch block.

  • The try block contains the code that may throw an exception.
  • The catch block contains the code that will be executed if an exception is thrown.
  • The finally block is optional and is used to execute code regardless of whether an exception is thrown or not. The finally block is also used to perform any cleanup operations that may be required.
  • The finally block is optional and can be omitted if it is not required.
    The try-catch-finally block is used to handle errors in better way.
  • async function shoppingFlow() {
        function placeOrder() {
            return new Promise(resolve => {
                setTimeout(() => {
                    console.log(" Order placed");
                    resolve("Package delivered");
                }, 2000); // 2 seconds
            });
        }
    
        function openPackage(packageInfo) {
            return new Promise(resolve => {
                setTimeout(() => {
                    console.log(` Opened: ${packageInfo}`);
                    resolve("Item used");
                }, 7000); // 7 seconds
            });
        }
    
        try{
            console.log(" Starting online shopping...");
        const delivery = await placeOrder();     // Takes 2 sec
        const result = await openPackage(delivery); // Takes 7 sec
        console.log(" Done:", result);
        } catch(error){
            console.log("Error:", error);
        }
    }
    
    console.log("Welcome to myCart.com");
    shoppingFlow();
    ๐Ÿ“ขImportant Note๐Ÿ“ข

    How did you feel about this post?

    ๐Ÿ˜ ๐Ÿ™‚ ๐Ÿ˜ ๐Ÿ˜• ๐Ÿ˜ก

    Was this helpful?

    ๐Ÿ‘ ๐Ÿ‘Ž